<?php
/**
 * Created by PhpStorm.
 * User: CYJiao
 * Date: 6/21/15
 * Time: 20:42
 */

class EHRController extends Controller{

    /**
     * Method returning filters array.
     */
    public function filters()
    {
        return array(
            'accessControl',//Performs access control for CRUD operations
        );
    }

    /**
     * Defines User Access Level.
     */
    public function accessRules()
    {
        return array(
            array('allow',
                'actions'=>array(),//Actions allowed
                'roles'=>array('@'),//Roles allowed to perform actions
            ),
            array('deny',
                'actions'=>array(),//Actions not allowed
                'roles'=>array('*'),//Roles not allowed to perform actions
            ),
        );
    }

    /**
     * Declares class-based actions.
     */
    public function actions(){
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'height'=>37,
                'minLength'=>4,
                'maxLength'=>6,
                'backColor'=>0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page'=>array(
                'class'=>'CViewAction',
            ),
        );
    }

    /**
     * Get ID from ID Server
     */
    private function getAutoID(){
        $id = curl_init();
        curl_setopt($id, CURLOPT_HEADER, 0);
        curl_setopt($id, CURLOPT_VERBOSE, 0);
        curl_setopt($id, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($id, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
        curl_setopt($id, CURLOPT_POST, true);
        curl_setopt($id, CURLOPT_URL, 'http://120.24.170.79:8080/push_call_server/get-id.do?accessToken=25da2c6fc3b8e5cfcd460b3367f7788e&logicid=8');
        $responseID = curl_exec($id);
        $result = json_decode($responseID,true);
        if($result['code']==0){
            return $result['content']['id'];
        }
    }

    /******************************************************************************************
     * Functions in Patient EHR
     ******************************************************************************************/

    /**
     * Get Patient EHR
     * @param bigint $pk_outpatient_id
     */
    public function actionGetPatientEHR($pk_outpatient_id){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $this->layout='main';
            $this->render('/ehr/patientehr',array('pk_outpatient_id'=>$pk_outpatient_id));
        }
        else
            $this->redirect(array('site/login'));//View redirection
    }

    /**
     * Add Patient EHR
     * @param bigint $pk_outpatient_id
     */
    public function actionAddPatientEHR($pk_outpatient_id){
        //Getting events active count,ticket sold from last login,new user registered after last login
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $this->layout='main';
            $sql = "SELECT * FROM tbl_outpatients WHERE pk_outpatient_id = '{$pk_outpatient_id}'";
            $outpatient = Yii::app()->db->createCommand($sql)->queryRow();

            $sql = "SELECT * FROM tbl_outpatient_locations WHERE pk_fk_outpatient_id='{$pk_outpatient_id}'";
            $outpatientLocation = Yii::app()->db->createCommand($sql)->queryRow();

            //Action logging
            // $log = new Log600100(); //Create new empty record
            // $log->action = 'add_patientEHR';//Saving the action type
            // $log->create_time = new CDbExpression('NOW()');//Saving date and time
            // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
            // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
            // $log->target = '';//针对对象
            // $log->save(false);//Saving the entire record with validation

            $this->render('/ehr/addpatientehr',
                array(
                    'pk_outpatient_id'=>$pk_outpatient_id,
                    'outpatient'=>$outpatient,
                    'outpatientLocation'=>$outpatientLocation
                )
            );
        }
        else
            $this->redirect(array('site/login'));//View redirection
    }

    /**
     * Get Patient EHR Content
     * @param bigint $pk_outpatient_ehr_id
     */
    public function actionGetPatientEHRContent($pk_outpatient_ehr_id){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            // Find or EHR information
            $ehrInfo = TblOutpatientEhr::model()->findByAttributes(array('pk_outpatient_ehr_id'=>$pk_outpatient_ehr_id));
            // Find the doctor who create the EHR
            $doctorInfo = TblDoctorInformation::model()->findByAttributes(array('pk_fk_doctor_id'=>$ehrInfo->fk_doctor_id));
            // Find the outpatient information
            $outpatientInfo = TblOutpatients::model()->findByAttributes(array('pk_outpatient_id'=>$ehrInfo->fk_outpatient_id));
            // Find the outpatient location
            $outpatientLocation = TblOutpatientLocations::model()->findByAttributes(array('pk_fk_outpatient_id'=>$ehrInfo->fk_outpatient_id));

            // Compare the creator and doctor is the same person or not
            if(Yii::app()->session['id']==$ehrInfo->fk_doctor_id){
                $same = 1;
            }else {
                $same = 2;
            }

            // $log = new Log600100(); //Create new empty record
            // $log->action = 'get_patientEHR';//Saving the action type
            // $log->create_time = new CDbExpression('NOW()');//Saving date and time
            // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
            // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
            // $log->target = '';//针对对象
            // $log->save(false);//Saving the entire record with validation

            $this->layout='main';
            $this->render('/ehr/patientehrcontent',
                array(
                    'creator_name'=>$doctorInfo->true_name,
                    'outpatientInfo'=>$outpatientInfo,
                    'outpatientLocation'=>$outpatientLocation,
                    'ehrInfo'=>$ehrInfo,
                    'same'=>$same
                )
            );
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    /**
     * Save Patient EHR
     */
    public function actionSavePatientEHR(){
        $result = array('status'=>0,'result'=>0);
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $ehr = new TblOutpatientEhr();
            $patient = TblOutpatients::model();
            
            $ehr->attributes = $_POST;
            $ehr->fk_doctor_id = Yii::app()->session['id'];
            $ehr->invalid = 1;
            $d = date('Y-m-d h:i:s');
            $ehr->ehr_time = $d;
            $ehr->create_time = $d;
            $ehr->update_time = $d;
            $ehr->marriage = 1;
            $ehr->handedness = 1;

            $patient_detail = array('weight'=>$_POST['weight'],
                'stature'=>$_POST['stature'],
                'alcohol'=>$_POST['alcohol'],
                'smoke'=>$_POST['smoke'],
                'allergy'=>$_POST['allergy'],
                'occupation'=>$_POST['occupation'],
                'phone'=>$_POST['phone'],
                'dob'=>$_POST['dob']);

            $ehr->pk_outpatient_ehr_id = $this->getAutoID();
            if($ehr->save()){

                // $log = new Log600100(); //Create new empty record
                // $log->action = 'save_patientEHR';//Saving the action type
                // $log->create_time = new CDbExpression('NOW()');//Saving date and time
                // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
                // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
                // $log->target = $ehr->pk_outpatient_ehr_id;//针对对象
                // $log->save(false);//Saving the entire record with validation

                $result['result'] = $ehr->pk_outpatient_ehr_id;
                $patient->updateByPk($_POST['fk_outpatient_id'],$patient_detail);//更新病例时候把病人相关信息更新到病人表
            }else{
                $result['status'] = 1;
                $result['result'] = json_encode($ehr->getErrors());
            }

        }
        else
            $result = array('status'=>2,'result'=>0);
        echo json_encode($result);
    }

    public function actionDelPatientEHR(){//废除病例
        $result = array('status'=>0,'result'=>0);
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $ehr = TblOutpatientEhr::model();
            $data['del_reason'] = $_POST['del_reason'];
            $data['invalid_time'] = date('Y-m-d h:i:s');
            $data['invalid'] = 2;
            if(!$ehr->updateByPk($_POST['pk_outpatient_ehr_id'],$data)){
                $result['status'] = 1;
                $result['result'] = json_encode($ehr->getErrors());
            }else{
                // $log = new Log600100(); //Create new empty record
                // $log->action = 'del_patientEHR';//Saving the action type
                // $log->create_time = new CDbExpression('NOW()');//Saving date and time
                // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
                // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
                // $log->target = $_POST['pk_outpatient_ehr_id'];//针对对象
                // $log->save(false);//Saving the entire record with validation
            }
        }
        else
            $result = array('status'=>2,'result'=>0);
        echo json_encode($result);
    }

    /**
     * Update Patient EHR
     * @param bigint $pk_outpatient_id
     */
    public function actionUpdatePatientEHR($pk_outpatient_id){
        $result = array('status'=>0,'result'=>0);
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $ehr = new TblOutpatientEhr();
            $ehr->attributes = $_POST;
            if($ehr->validate()){
                $ehr->pk_outpatient_ehr_id = $this->getAutoID();
                if($ehr->save()){

                    $log = new Log600100(); //Create new empty record
                    $log->action = 'update_patientEHR';//Saving the action type
                    $log->create_time = new CDbExpression('NOW()');//Saving date and time
                    $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
                    $log->fk_user_id = Yii::app()->session['id'];//Saving user id
                    $log->target = $pk_outpatient_id;//针对对象
                    $log->save(false);//Saving the entire record with validation

                    $result['result'] = $ehr->pk_outpatient_ehr_id;
                }else{
                    $result['status'] = 1;
                }
            }
        }
        else
            $result = array('status'=>2,'result'=>0);
        echo json_encode($result);
    }

    /**
     * Get all outpatient EHR
     * @param bigint $pk_outpatient_id
     */
    public function actionGetEHRS($pk_outpatient_id){
        $sql = "SELECT pk_outpatient_ehr_id,invalid,fk_outpatient_id,fk_user_id,fk_doctor_id,create_time FROM tbl_outpatient_ehr WHERE fk_outpatient_id = '{$pk_outpatient_id}' order by create_time desc";
        //$sql = "SELECT op.pk_outpatient_id, op.true_name, op.gender, op.dob FROM tbl_outpatients op WHERE pk_outpatient_id in (SELECT do.fk_outpatient_id FROM tbl_doctors_has_tbl_outpatients do WHERE do.fk_doctor_id=".$pk_doctor_id.") ORDER BY convert(op.true_name using gbk) asc";
        $outPatients = Yii::app()->db->createCommand($sql)->queryAll();
        $list = array();
        foreach($outPatients as $row){

            $create_time = strtotime ($row['create_time']);
            $yeah = date('Y',$create_time);
            $month = date('m',$create_time);
            if(!isset($list[$yeah])){
                $list[$yeah] = array('id'=>$yeah,'date'=>$yeah.'年','children'=>array());
            }

            if(!isset($list[$yeah]['children'][$month])){
                $list[$yeah]['children'][$month] = array('id'=>date('Y-m',$create_time),'date'=>$month.'月','children'=>array());
            }
            $day = date('d',$create_time);
            //Yii::log('d='.$day,CLogger::LEVEL_ERROR);
            if(!isset($list[$yeah]['children'][$month]['children'][$day])){
                $list[$yeah]['children'][$month]['children'][$day] = array();
            }
            $list[$yeah]['children'][$month]['children'][$day][] = $row; //每一天多条
            //Yii::log(json_encode($list),CLogger::LEVEL_ERROR);
        }// end foreach
        

        $result = array();

        foreach ($list as $rs) {
            $children = array();
            foreach ($rs['children'] as $monthNum=>$month){
                
                $monthChils = array();
                foreach ($month['children'] as $dayNum=>$day){

                    if(count($day)>1){
                        //一天有多条记录

                        $dayRs = array('id'=>$yeah.$monthNum.$dayNum,'date'=>$monthNum.'月'.$dayNum,'children'=>array());
                        foreach ($day as $row){
                            if($row['invalid']!=1 && $row['fk_doctor_id']!=Yii::app()->session['id']) break;
                            $create_time = strtotime($row['create_time']);
                            $dayRs['children'][] = array('id'=>$row['pk_outpatient_ehr_id'],'ehr_id'=>$row['pk_outpatient_ehr_id'],
                                'date'=>date('h点i分',$create_time),'iconCls'=>$row['invalid']==1?'icon-ok':'icon-cancel');
                        }
                        if(!empty($dayRs['children'])) $monthChils[] = $dayRs;
                    }else{
                        //一天只有一条记录
                        if($day[0]['invalid']!=1 && $day[0]['fk_doctor_id']!=Yii::app()->session['id']) break;
//     					Yii::log(json_encode($day[0]),CLogger::LEVEL_ERROR);
                        $create_time = strtotime($day[0]['create_time']);
                        $dayRs = array('id'=>date('Ymd',$create_time),'ehr_id'=>$day[0]['pk_outpatient_ehr_id'],
                            'date'=>date('m月d日',$create_time),'iconCls'=>$day[0]['invalid']==1?'icon-ok':'icon-cancel');
                        $monthChils[] = $dayRs;
                    }// end if
                    if(!empty($monthChils)) 	$month['children'] = $monthChils;
                }// end foreach ($month['children'] as $day){
                if(!empty($monthChils))   			$children[] = $month;

                
            }// end foreach ($rs['children'] as $month){
            $rs['children'] = $children;
            if(!empty($children))   		$result[] = $rs;
        }// end foreach ($list as $rs) {
        // $log = new Log600100(); //Create new empty record
        // $log->action = 'list_patientEHR';//Saving the action type
        // $log->create_time = new CDbExpression('NOW()');//Saving date and time
        // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
        // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
        // $log->target = $pk_outpatient_id;//针对对象
        // $log->save(false);//Saving the entire record with validation
       echo json_encode($result);
    }

}